package com.pervasa.demo.re.impl.data;

public class TFMEvent extends Event {

	private Event event;
	private TFM tfm;
	private int counter;
	private long nextTime;
	
	public TFMEvent(String name, Event event, TFM tfm) {
		super(name);
		this.event = event;
		this.tfm = tfm;
		this.counter = 0;
		this.nextTime = 0;
		event.addEventListener(this);
	}

	@Override
	public void evaluate(Object arg) {
		if (tfm.getW().isActive()) {
			if (event.isTriggered()) {
				++counter;
				if (counter >= tfm.getFr() && event.getStartTime() >= nextTime) {
					setTriggered(true);
					nextTime = event.getStartTime() + tfm.getFe() * 1000;
					counter = 0;
				}
				else if (isTriggered()) {
					setTriggered(false);
				}
			}
		}
		else if (isTriggered()) {
			setTriggered(false);
		}
	}

	@Override
	public String getExpression() {
		return tfm + "(" + event.getName() + ")";
	}
	
}
